//
//  VCOfReadWeb.m
//  LCOnePsychology
//
//  Created by li cheng on 16/9/21.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "VCOfReadWeb.h"
#import "BaseView.h"
#import "MJMacro.h"
#import "Masonry.h"
#import "VCOfLogining.h"
#import "ZWYNetTool.h"
#import "DataOfReplyInformation.h"
#import "RootClassOfReplyInformation.h"
#import "UserOfDataReplyInformation.h"
@interface VCOfReadWeb ()<UIWebViewDelegate>
@property (nonatomic, strong) BaseView *viewOfBackground;
@property (nonatomic, strong) UITextView *textView;
@property (nonatomic, strong)UIWebView *webView;
@property (nonatomic, strong)UIActivityIndicatorView *action;
@property (nonatomic, assign) CGSize keyboardSize;
@property (nonatomic, strong) RootClassOfReplyInformation *rootClassOfReplyInformation;
@property (nonatomic, strong) UILabel *supportLabel;
@property (nonatomic, strong) UILabel *commentsLabel;
@property (nonatomic, assign) NSInteger numberOfWebFinish;
@end

@implementation VCOfReadWeb

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self handleBackButton];
    self.numberOfWebFinish = 0;
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.delegate = self;
    // 自适应 webview 大小
    self.webView.scalesPageToFit = YES;
    [self.view addSubview:self.webView];
    // 创建下面的 barView
    [self createBarView];
    // 创建回复
    [self createReply];
    // 给键盘注册通知
    [self registerForKeyboardNotifications];
    // 数据请求回复的详情
    [self handleDataOfReplyInformation];
    
}
#pragma mark - 视图出现
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString :_stringURL]];
    [self.webView loadRequest:request];
    
}

#pragma mark - 数据请求
- (void)handleDataOfReplyInformation{
    [ZWYNetTool GET:[NSString stringWithFormat:@"http://yiapi.xinli001.com/v2/yi/article-new-detail.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0&id=%@&token=0d4eeb8732f9ae2c73401002570ceb93", _myID] andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSLog(@"%@", result);
        _rootClassOfReplyInformation = [RootClassOfReplyInformation modelDic:result];
        _supportLabel.text = _rootClassOfReplyInformation.data.zannum;
        _commentsLabel.text = _rootClassOfReplyInformation.data.commentnum;
    } andFailureBlock:^(NSError *error) {
        
    }];
}
#pragma mark - 创建 评论 的 输入框
- (void)createReply{
    self.viewOfBackground = [[BaseView alloc] initWithFrame:CGRectMake(0, -200, SCREEN_WIDTH, 200)];
    // 放弃回复 button
    UIButton *buttonOfResignReply = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 40, 40)];
    [buttonOfResignReply setTitle:@"✖️" forState:UIControlStateNormal];
    [buttonOfResignReply addTarget:self action:@selector(giveUpReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:buttonOfResignReply];
    // label 评论给
    UILabel *labelOfComments = [[UILabel alloc] init];
    labelOfComments.text = @"评论";
    [self.viewOfBackground addSubview:labelOfComments];
    [labelOfComments mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.viewOfBackground).offset(0);
        make.width.mas_offset(60);
        make.height.mas_offset(20);
        make.top.equalTo(self.viewOfBackground).offset(20);
    }];
    // 回复 button
    UIButton *buttonOfReply = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 10, 40, 40)];
    [buttonOfReply setTitle:@"✔️" forState:UIControlStateNormal];
    [buttonOfReply addTarget:self action:@selector(sureReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:buttonOfReply];
    // 输入的视图
    self.textView = [[UITextView alloc] init];
    [self.viewOfBackground addSubview:_textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.viewOfBackground).offset(15);
        make.right.equalTo(self.viewOfBackground).offset(-15);
        make.bottom.equalTo(self.viewOfBackground).offset(-15);
        make.height.mas_offset(120);
    }];
    self.viewOfBackground.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    [self.view addSubview:_viewOfBackground];
//    // 得到键盘的高度 plus下为271
//    CGFloat height = [[noti.userInfo objectForKey:@"UIKeyboardFrameEndUserInfoKey"] CGRectValue].size.height;
//    // 改变 commentBar 的位置
//    self.commentBar.transform = CGAffineTransformMakeTranslation(0, -height);
    
}
#pragma mark - 回复的功能实现
- (void)reply:(UIButton *)button{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *user_id = [user objectForKey:@"user_id"];
    if (user_id){
        // textView 变成第一响应者
        [_textView becomeFirstResponder];
    } else {
        // 跳转到登录界面
        VCOfLogining *vcOfLogining = [[VCOfLogining alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vcOfLogining];
        [self presentViewController:navi animated:YES completion:^{
            
        }];
    }
}
#pragma mark - 放弃回复按钮的方法实现
- (void)giveUpReply:(UIButton *)button{
    [_textView resignFirstResponder];
}
#pragma mark - 确认回复
- (void)sureReply:(UIButton *)button{
        NSLog(@"%@", _textView.text);
    [ZWYNetTool POST:@"http://yiapi.xinli001.com/h5/yi/article-new-comm.json" andBody:[NSString stringWithFormat:@"token=0d4eeb8732f9ae2c73401002570ceb93&object_id=%@&content=%@&reply_object_id=0&reply_user_id=0&pid=0", _myID, _textView.text] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/x-www-form-urlencoded; charset=UTF-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        [_textView resignFirstResponder];
        [_webView reload];
    } andFailureBlock:^(NSError *error) {
        
    }];
   
}
#
#pragma mark - 创建 下面的 barView
- (void)createBarView{
    BaseView *barView = [[BaseView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
    barView.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    [self.view addSubview:barView];
    //  创建分享的按钮
    UIButton *enshrineButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [enshrineButton addTarget:self action:@selector(clickEnshrineButton:) forControlEvents:UIControlEventTouchUpInside];
    [enshrineButton setImage:[UIImage imageNamed:@"Collect"] forState:UIControlStateNormal];
    [barView addSubview:enshrineButton];
    [enshrineButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(barView).offset(0);
        make.right.equalTo(barView).offset(-10);
        make.width.mas_offset(44);
    }];
    // 评论的 button
    UIButton *commentsButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [commentsButton setImage:[UIImage imageNamed:@"Comment_32-1"] forState:UIControlStateNormal];
    [commentsButton addTarget:self action:@selector(lookComments:) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:commentsButton];
    [commentsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(barView).offset(0);
        make.right.equalTo(enshrineButton.mas_left).offset(-20);
        make.width.mas_offset(44);
    }];
    self.commentsLabel = [[UILabel alloc] init];
    self.commentsLabel.text = @"0";
    self.commentsLabel.textAlignment = 1;
    self.commentsLabel.backgroundColor = [UIColor redColor];
    self.commentsLabel.textColor = [UIColor whiteColor];
    [barView addSubview:_commentsLabel];
    [self.commentsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(barView).offset(2);
        make.left.equalTo(commentsButton.mas_right).offset(-5);
        make.width.mas_offset(30);
        make.height.mas_offset(16);
    }];
    // 点赞的 button
    UIButton *supportButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [supportButton setImage:[UIImage imageNamed:@"Support_32-1"] forState:UIControlStateNormal];
    [supportButton addTarget:self action:@selector(clickSupport:) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:supportButton];
    [supportButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(barView).offset(0);
        make.right.equalTo(commentsButton.mas_left).offset(-20);
        make.width.mas_offset(44);
    }];
    // 点赞的 label
    self.supportLabel = [[UILabel alloc] init];
    self.supportLabel.backgroundColor = [UIColor redColor];
    self.supportLabel.text = @"0";
    self.supportLabel.textAlignment = 1;
    self.supportLabel.textColor = [UIColor whiteColor];
    [barView addSubview:_supportLabel];
    [self.supportLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(barView).offset(2);
        make.left.equalTo(supportButton.mas_right).offset(-15);
        make.width.mas_offset(30);
        make.height.mas_offset(16);
    }];
    // 添加回复的 button
    UIButton *replyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [barView addSubview:replyButton];
    [replyButton addTarget:self action:@selector(reply:) forControlEvents:UIControlEventTouchUpInside];
    [replyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(barView).offset(20);
        make.centerY.mas_equalTo(barView);
        make.height.mas_offset(30);
        make.right.equalTo(supportButton.mas_left).offset(-10);
    }];
    [replyButton setTitle:@"  写评论..." forState:UIControlStateNormal];
    [replyButton setTitleColor:[UIColor colorWithRed:0.80 green:0.80 blue:0.80 alpha:1.00] forState:UIControlStateNormal];
    replyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    // 设置边界弧度
    [replyButton.layer setCornerRadius:5];
    // 设置边界的宽度
    [replyButton.layer setBorderWidth:1];
    // 设置按钮的边界颜色
    UIColor *coloroo = [UIColor colorWithRed:0.008 green:0.008 blue:0.004 alpha:1.000];
    [replyButton.layer setBorderColor:coloroo.CGColor];

}
#pragma mark - 收藏 button 的实现
- (void)clickEnshrineButton:(UIButton *)button{
    NSLog(@"执行了收藏的功能");
    [ZWYNetTool POST:@"http://yiapi.xinli001.com/v2/yi/toggle-article-favorite.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:[NSString stringWithFormat:@"{\"token\":\"0d4eeb8732f9ae2c73401002570ceb93\",\"article_id\":\"%@\"}", _myID] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/json"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSLog(@"%@", result);
        if ([result[@"message"] isEqualToString:@"已收藏"]) {
            [self pleaseWait];
        } else {
            [self pleaseWaitTwo];
        }
    } andFailureBlock:^(NSError *error) {
        
    }];
   
}
#pragma mark - 点赞 button 的实现
- (void)clickSupport:(UIButton *)button{
    [ZWYNetTool POST:@"http://yiapi.xinli001.com/v2/yi/toggle-article-like.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:[NSString stringWithFormat:@"{\"token\":\"0d4eeb8732f9ae2c73401002570ceb93\",\"article_id\":\"%@\"}", _myID] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type": @"application/json"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        [self handleDataOfReplyInformation];
    } andFailureBlock:^(NSError *error) {
        
    }];
}
#pragma mark - 点下面 barView 的评论的 button查看对应的评论
- (void)lookComments:(UIButton *)button{
    _webView.scrollView.contentOffset = CGPointMake(0, _webView.scrollView.contentSize.height - SCREEN_HEIGHT * 0.25 * [_rootClassOfReplyInformation.data.commentnum intValue] - 400);
}
#pragma mark - 设置返回按钮
- (void)handleBackButton{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回" style:UIBarButtonItemStylePlain target:self action:@selector(backButton:)];
}
#pragma mark - 点击返回
- (void)backButton:(UIBarButtonItem *)barButton{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 开始的时候给他加载的效果
- (void)webViewDidStartLoad:(UIWebView *)webView {
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor lightGrayColor]];
    [view setAlpha:0.5];
    [self.view addSubview:view];
    self.action = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];// 指定进度轮大小
    [self.action setCenter:view.center];// 指定进度轮中心点
    [self.action setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];// 设置进度轮显示类型
    [view addSubview:self.action];
    [self.action startAnimating];
}
#pragma mark - web 加载结束
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self.action stopAnimating];
    UIView *view = (UIView *)[self.view viewWithTag:108];
    [view removeFromSuperview];
    if (_numberOfWebFinish != 0) {
        webView.scrollView.contentOffset = CGPointMake(0, webView.scrollView.contentSize.height - SCREEN_HEIGHT);
    }
    UIWebView *web = webView;
    
    //获取所有的html
    
    NSString *allHtml = @"document.documentElement.innerHTML";
    
    //获取网页title
    
    NSString *htmlTitle = @"document.title";
    NSLog(@"htmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitlehtmlTitle--------%@", htmlTitle);
    
    
    //获取网页的一个值
    
    NSString *htmlNum = @"document.getElementById('title').innerText";
    
    //获取到得网页内容
    
    NSString *allHtmlInfo = [web stringByEvaluatingJavaScriptFromString:allHtml];
    
    NSLog(@"allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo,allHtmlInfo%@",allHtmlInfo);
    
    NSString *titleHtmlInfo = [web stringByEvaluatingJavaScriptFromString:htmlTitle];
    
    NSLog(@"titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,titleHtmlInfo,%@",titleHtmlInfo);
    
    NSString *numHtmlInfo = [web stringByEvaluatingJavaScriptFromString:htmlNum];
    
    NSLog(@"numHtmlInfo.numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo,numHtmlInfo%@",numHtmlInfo);

}
#pragma mark - 错误警告
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [self.action stopAnimating];
    UIView *view = [self.view viewWithTag:108];
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentCenter;
    label.frame = CGRectMake(0, 0, self.view.frame.size.width, 40);
    label.text = @"此网站无效";
    label.center = self.view.center;
    [view addSubview:label];
}
#pragma 给键盘注册通知
- (void)registerForKeyboardNotifications
{
    // 给键盘出现通知添加方法选择器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    // 给键盘隐藏添加方法选择器
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
    // 给键盘改变添加方法选择器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWasChange:) name:UIKeyboardDidChangeFrameNotification object:nil];
}
#pragma mark - 给键盘出现通知添加方法选择器
- (void) keyboardWasShown:(NSNotification *)notif
{
//    NSDictionary *info = [notif userInfo];
//    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    _keyboardSize = [value CGRectValue].size;
//    NSLog(@"%f", _keyboardSize.height);
//    ///keyboardWasShown = YES;
//    _viewOfBackground.frame = CGRectMake(0, SCREEN_HEIGHT - _keyboardSize.height - 200, SCREEN_WIDTH, 200);
}
#pragma mark - 给键盘隐藏添加方法选择器
- (void) keyboardWasHidden:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    // keyboardWasShown = NO;
    _viewOfBackground.frame = CGRectMake(0, -200, SCREEN_WIDTH, 200);
}
#pragma mark - 给肩膀改变添加方法选择器
- (void)KeyboardWasChange:(NSNotification *)notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    // keyboardWasShown = NO;
    _viewOfBackground.frame = CGRectMake(0, SCREEN_HEIGHT - _keyboardSize.height - 200, SCREEN_WIDTH, 200);
}
#pragma mark - 还未开放此功能
- (void)pleaseWait{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"已经收藏了" message:@"去别的地方看看" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 还未开放此功能
- (void)pleaseWaitTwo{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"已经取消收藏了" message:@"还要再看看吗" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:^{
        
    }];
}
#pragma mark - 其他, 内存问题.
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
